package com.flower8.controller;

import com.flower8.dto.ActiveCrowdfundDto;
import com.flower8.dto.ActiveOfferDto;
import com.flower8.dto.UserDto;
import com.flower8.model.CrowdfundPay;
import com.flower8.service.CrowdfundService;
import com.flower8.sysconfig.constants.MsgConstants;
import com.flower8.utils.PageData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 众筹控制层
 * @Author: tanglin
 * @Date: 2019/09/19 15:29
 * @Version: 1.0
 */
@RestController
@RequestMapping("/crowdfund")
public class CrowdfundController extends  BaseController{
    private static final Logger log = LoggerFactory.getLogger(CrowdfundController.class);

    @Autowired
    private CrowdfundService crowdfundService;

    /**
     * 查询所有用户众筹列表
     * @param request
     * @return
     */
    @RequestMapping("/getCrowdfundList")
    public Object getCrowdfundList(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询所有用户众筹列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            List<ActiveCrowdfundDto> data =  crowdfundService.getCrowdfundList(pd);
            int total = crowdfundService.getCrowdfundListCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
            Map<String, Object> dataMap = (Map<String, Object>) responseResultForSuccess(res);
            // 兼容旧网页
            dataMap.put("recordsTotal", total);   //dataTable分页需要
            dataMap.put("recordsFiltered", total);//dataTable分页需要
            dataMap.put("draw", pd.get("draw").toString());//dataTable分页需要
            return dataMap;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     * 根据众筹单id查询
     * @param id 众筹单id
     * @return
     */
    @RequestMapping("/getCrowdfundById")
    public Object getCrowdfundById(@RequestParam Long id){
        logBefore(log, "++++++++++ 根据众筹单id查询 ++++++++++");
        try{
            ActiveCrowdfundDto crowdfund = crowdfundService.getCrowdfundById(id);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("crowdfund", crowdfund);
            return responseResultForSuccess(dataMap);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     * 修改众筹单状态
     * @param request
     * @return
     */
    @RequestMapping("/editCrowdfundStatus")
    public Object editCrowdfundStatus(HttpServletRequest request) {
        logBefore(log, "++++++++++ 修改众筹单状态 ++++++++++");
        PageData pd = new PageData(request);

        try {
            long id = Long.valueOf(pd.get("id").toString());
            long status = Long.valueOf(pd.get("status").toString());
            ActiveCrowdfundDto activeCrowdfundDto = crowdfundService.getCrowdfundById(id);
            long oldStatus = activeCrowdfundDto.getStatus();
            if (status == 1) {
                if (oldStatus != 0 && oldStatus != 22) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 2) {
                if (oldStatus != 21) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 4) {
                if (oldStatus != 1 && oldStatus != 22) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 5) {
                if (oldStatus != 0) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 21) {
                if (oldStatus != 2) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else {
                return responseResultForError("该众筹单状态已被其他用户更新");
            }
            crowdfundService.editCrowdfundStatus(pd);
            logAfter(log);
            return responseResultForSuccess(null, "操作成功");
        }catch (Exception e){
            log.error(e.getMessage());
            return responseResultForError("操作失败");
        }
    }

    /**
     * 修改用户的信用分
     * @param request
     * @return
     */
    @RequestMapping("/editCreditScoreByUserId")
    public Object editCreditScoreByUserId(HttpServletRequest request) {
        PageData pd = new PageData(request);
        logBefore(log, "++++++++++ 修改用户id为"+pd.getString("userId")+"的信用分 ++++++++++");
        try {
            Object statusObj = pd.get("status");
            if (statusObj != null) {
                long id = Long.valueOf(pd.get("id").toString());
                long status = Long.valueOf(statusObj.toString());
                ActiveCrowdfundDto activeCrowdfundDto = crowdfundService.getCrowdfundById(id);
                long oldStatus = activeCrowdfundDto.getStatus();
                if (status == 4) {
                    if (oldStatus != 1 && oldStatus != 22) {
                        return responseResultForError("该用户状态已被其他用户更新");
                    }
                } else {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            }
            crowdfundService.editCreditScoreByUserId(pd);
            logAfter(log);
            return responseResultForSuccess(null,"操作成功");
        }catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
            return responseResultForError("操作失败");
        }
    }

    /**
     * 修改众筹单
     * @param request
     * @return
     */
    @RequestMapping("/updCrowd")
    public Object updCrowd(HttpServletRequest request) {
        PageData pd = new PageData(request);
        logBefore(log, "++++++++++ 修改众筹单 ++++++++++");
        try {
            long id = Long.valueOf(pd.get("cid").toString());
            long status = Long.valueOf(pd.get("status").toString());
            ActiveCrowdfundDto activeCrowdfundDto = crowdfundService.getCrowdfundById(id);
            long oldStatus = activeCrowdfundDto.getStatus();
            if (status == 1) {
                if (oldStatus != 0 && oldStatus != 22) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 2) {
                if (oldStatus != 21) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 4) {
                if (oldStatus != 1 && oldStatus != 22) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 5) {
                if (oldStatus != 0) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else if (status == 21) {
                if (oldStatus != 2) {
                    return responseResultForError("该众筹单状态已被其他用户更新");
                }
            } else {
                return responseResultForError("该众筹单状态已被其他用户更新");
            }
            crowdfundService.updCrowd(pd);
            logAfter(log);
            return responseResultForSuccess(null,"操作成功");
        }catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
            return responseResultForError("操作失败");
        }
    }

    /**
     * 查询众筹单筹款详情列表
     * @param request
     * @return
     */
    @RequestMapping("/getCrowdfundDetailList")
    public Object getCrowdfundDetailList(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询众筹单筹款详情列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            List<ActiveOfferDto> data =  crowdfundService.getCrowdfundDetailList(pd);
            int total = crowdfundService.getCrowdfundDetailListCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
            Map<String, Object> dataMap = (Map<String, Object>) responseResultForSuccess(res);
            // 兼容旧网页
            dataMap.put("recordsTotal", total);   //dataTable分页需要
            dataMap.put("recordsFiltered", total);//dataTable分页需要
            dataMap.put("draw", pd.get("draw").toString());//dataTable分页需要
            return dataMap;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    /**
     * 打款记录查询列表
     * @param request
     * @return
     */
    @RequestMapping("/tranferMoneyList")
    public Object tranferMoneyList(HttpServletRequest request){
        logBefore(log, "++++++++++ 打款记录查询列表 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            List<CrowdfundPay> data =  crowdfundService.tranferMoneyList(pd);
            int total = crowdfundService.tranferMoneyCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
            Map<String, Object> dataMap = (Map<String, Object>) responseResultForSuccess(res);
            // 兼容旧网页
            dataMap.put("recordsTotal", total);   //dataTable分页需要
            dataMap.put("recordsFiltered", total);//dataTable分页需要
            dataMap.put("draw", pd.get("draw").toString());//dataTable分页需要
            return dataMap;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }


    /**
     * 查询打款记录
     * @param request
     * @return
     */
    @RequestMapping("/tranferMoneyDetail")
    public Object tranferMoneyDetail(HttpServletRequest request){
        logBefore(log, "++++++++++ 查询打款记录 ++++++++++");
        PageData pd = new PageData(request);

        pd.put("start", Integer.parseInt( pd.get("start").toString() ) );
        pd.put("length", Integer.parseInt( pd.get("length").toString() ) );

        Map res = new HashMap();
        try {
            String str = pd.getString("crowdfundIds");
            String[] permiArray = str.split(",");
            pd.put("permiArray",permiArray);

            List<Map> data =  crowdfundService.tranferMoneyDetail(pd);
            int total = crowdfundService.tranferMoneyDetailCount(pd);
            res.put("data", data);
            res.put("recordsTotal", total);   //dataTable分页需要
            res.put("recordsFiltered", total);//dataTable分页需要
            res.put("draw", pd.get("draw").toString());//dataTable分页需要
            logAfter(log);
            Map<String, Object> dataMap = (Map<String, Object>) responseResultForSuccess(res);
            // 兼容旧网页
            dataMap.put("recordsTotal", total);   //dataTable分页需要
            dataMap.put("recordsFiltered", total);//dataTable分页需要
            dataMap.put("draw", pd.get("draw").toString());//dataTable分页需要
            return dataMap;
        }catch (Exception e){
            e.printStackTrace();
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }
}
